﻿using System.Collections.Generic;
using System.Linq;
using Aocsoft.Infrastructure.DomainBase;
using Aocsoft.Infrastructure.RepositoryFramework;


namespace Aocsoft.Infrastructure.Repository.NHProvider
{
    using System;
    using NHibernate.Linq;
    public abstract class NHRepositoryBase<T> : RepositoryBase<T>, INHRepository<T>
       where T : EntityBase
    {
        public abstract NHibernate.ISession RepositContext { get; }

        protected NHRepositoryBase()
            : this(null)
        {
        }

        protected NHRepositoryBase(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        #region For UnitOfWork repository framework call
        protected override void PersistNewItem(T item)
        {
            this.RepositContext.Persist(item);
        }

        protected override void PersistUpdatedItem(T item)
        {
            this.RepositContext.Update(item);
        }

        protected override void PersistDeletedItem(T item)
        {
            this.RepositContext.Delete(item);
        }
        #endregion


        public override T FindBy(Guid key)
        {
            return this.RepositContext.Get<T>(key, NHibernate.LockMode.Read);
        }

        public override IList<T> FindAll()
        {
            return this.RepositContext.CreateCriteria<T>().List<T>();
        }

        public virtual IQueryable<T> GetBaseQuery()
        {
            return RepositContext.Query<T>();
        }

        public T Load(Guid key)
        {
            return RepositContext.Load<T>(key);
        }

        public override void RemoveAll(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate = null)
        {
            var query = predicate == null ? GetBaseQuery() : GetBaseQuery().Where(predicate);
            foreach (var item in query)
            {
                Remove(item);
            }
        }
    }
}
